package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.CheckGroupDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.CheckGroup;
import com.itheima.health.service.CheckGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = CheckGroupService.class)
@Slf4j
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupDao checkGroupDao;
    @Transactional
    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        log.info("[检查组-添加]data:{},checkitemIds:{}",checkGroup,checkitemIds);
        //1.插入基础信息
        checkGroupDao.insert(checkGroup);
        //2.插入关联表
        for (Integer checkitemId : checkitemIds) {
            checkGroupDao.insertCheckGroupAndCheckItem(checkGroup.getId(),checkitemId);
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        log.info("[检查组-分页查询]data:{}",queryPageBean);
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<CheckGroup> page=checkGroupDao.selectByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    //根据id查询
    @Override
    public CheckGroup findById(Integer id) {
        log.info("[检查组-根据id查询]id:{}",id);
        return checkGroupDao.selectById(id);
    }

    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer id) {
        log.info("[检查组-根据检查组id查询关联的检查项id集合]id:{}",id);
        return checkGroupDao.selectCheckItemIdsByCheckGroupId(id);
    }

    @Transactional
    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        log.info("[检查组-编辑]data:{},checkitemIds:{}",checkGroup,checkitemIds);
        //更新基本信息
        checkGroupDao.update(checkGroup);
        //更新关联信息
        //先删除原始关联
        checkGroupDao.deleteCheckGroupAndCheckItemByCheckGroupId(checkGroup.getId());
        //添加新的关联关系
        for (Integer checkitemId : checkitemIds) {
            checkGroupDao.insertCheckGroupAndCheckItem(checkGroup.getId(),checkitemId);
        }
    }

    @Override
    public List<CheckGroup> findAll(CheckGroup checkGroup) {
        log.info("[检查组-查询所有]data:{}",checkGroup);

        return checkGroupDao.selectAll(checkGroup);
    }
}
